package messenger;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Logger;

/**
 * 
 * @author JUNYONZH
 *
 */
public class MessengerServer {
	
	private ServerSocket server = null;
	private Logger log = Logger.getLogger("MessengerServer");
	private HashMap<String, MessengerSession> sessionMap = new HashMap<String, MessengerSession>();
	private HashMap<String, String> userMap = new HashMap<String, String>();
	
	public static void main(String[] args) {
		MessengerServer server = new MessengerServer();
		server.startServer();
//		server.stopServer();
	}
	
	public MessengerServer() {
		userMap.put("zjy", "zjy");
		userMap.put("song", "song");
	}
	
	public boolean checkUser(String user, String pwd) {
		String password = userMap.get(user);
		if(password != null && password.equals(pwd)) {
			return true;
		}
		return false;
	}
	
	public boolean startServer() {
		int port = 8081;
		Properties config = new Properties();
		try {
			config.load(this.getClass().getResourceAsStream("config.properties"));
			String portStr = config.getProperty("port");
			if(portStr != null && portStr.trim().length() > 0) {
				try {
					port = Integer.parseInt(portStr);
				} catch (NumberFormatException e) {
					log.info(portStr + " is not a valid port. Default port 8081 will be used");
				}
			}else {
				log.info("Port is not found. Default port 8081 will be used");
			}
		} catch (IOException e1) {
			log.info("File config.properties is not found. Default configuration will be used.");
			e1.printStackTrace();
		}
		
		log.info("Start MessengerServer at port " + port);
		try {
			server = new ServerSocket(port);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.severe("Start MessengerServer Failed");
			return false;
		}
		
		Thread serverDeamon = new Thread(new MessengerServerDeamon(this));
		serverDeamon.start();	
		log.info("Start MessengerServer successfully");
		return true;
	}
	
	public MessengerSession waitConnection() throws MessengerException {
		if(server == null || server.isClosed()) {
			throw new MessengerException("Server is invalid!");
		}
		Socket socket;
		try {
			socket = server.accept();
		} catch (IOException e) {
			e.printStackTrace();
			throw new MessengerException("IOException", e);
		}
		
		MessengerSession session = new MessengerSession(socket, null, false, null, 0);
		return session;
	}
	
	public boolean addSession(MessengerSession session) {
		if(session.getUser() == null || session.getUser().trim().length() == 0) {
			log.info("Add session to sessionMap failed!");
			return false;
		}
		sessionMap.put(session.getUser(), session);
		return true;
	}
	
	public MessengerSession removeSession(String user) {
		return sessionMap.remove(user);
	}
	
	public MessengerSession getSession(String user) {
		return sessionMap.get(user);
	}
	
	public String[] getFriendList(String user) {
		Set<String> userSet = sessionMap.keySet();
		if(userSet.size() <= 1)
			return null;
		int i = 0;
		String[] friendArray = new String[userSet.size()-1];
		for(String tmp : userSet) {
			if(!user.equals(tmp)) {
				friendArray[i++] = tmp;
			}
		}
		return friendArray;
	}
	
	public boolean isAction() {
		if(server == null || server.isClosed()) {
			return false;
		}
		return true;
	}
	
	public boolean stopServer() {
		log.info("Stop MessengerServer");
		try {
			server.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		log.info("MessengerServer is stopped");
		return true;
	}

}